package handler

import (
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"micros/api/params"
	"micros/golbal"
	"micros/inits"
	"micros/model"
	"net/http"
	"time"
)

func FriendShow(c *gin.Context) {
	req := params.FriendShow{}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user model.User

	golbal.DB.Where("mobile like ?  ", "%"+req.Mobile+"%").
		Find(&user)

	golbal.DB.Where("nickname like ?  ", "%"+req.NiceName+"%").
		Find(&user)
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友查询成功",
		"data": user,
	})
}

func AddFriend(c *gin.Context) {
	req := params.AddFriend{}
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	friend := model.Friend{

		UserId:   req.UserId,
		FriendId: req.FriendId,
		Remark:   req.Remark,
		Status:   "1",
	}

	golbal.DB.Debug().Create(&friend)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友添加成功",
	})
}

func FriendList(c *gin.Context) {
	list := params.FriendList{}
	if err := c.ShouldBind(&list); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	var user []model.FriendList

	key := fmt.Sprintf("friend_list")
	result, _ := golbal.Rdb.Get(inits.Ctx, key).Result()
	if result == "" {
		marshal, _ := json.Marshal(&user)
		golbal.Rdb.Set(inits.Ctx, key, marshal, time.Minute*10)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	golbal.DB.Model(&model.User{}).Select("users.*,friends.friend_id").
		Joins("join friends on friends.user_id=users.id").Where("friends.friend_id", list.FriendId).Scan(&user)

	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "好友列表查询成功",
		"data": user,
	})
}
